package Inet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;


public class TcpEchoServer_Dic {
    //ServerSocket 是服务器用的
    private ServerSocket serverSocket = null;

    public TcpEchoServer_Dic(int port) throws IOException {
        serverSocket = new ServerSocket(port);


    }

    public void start() throws IOException {
        System.out.println("服务器启动！");

        while (true) {
            //Socket 用于收接信息
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        //打印一个日志 说明客户端上线了
        System.out.printf("[%s:%d] 客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());

        //2、从 socket 中获取到流对象 来进行下一步的后续操作
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            //3、循环 因为针对一个连接也可能会有多个请求
            Scanner scanner = new Scanner(inputStream);
            while (true) {
                //3.1 读取请求并解析
                if(!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线\n",clientSocket.getInetAddress(),clientSocket.getPort());
                }
                String request = scanner.next();

                //3.2 解析请求并返回
                String response = process(request);
                outputStream.write(response.getBytes());

                //3.3 打印日志
                System.out.printf("[%s:%d] req=%s, resp=%s",clientSocket.getInetAddress(),clientSocket.getPort(),
                                        request,response);
            }
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("cat","小猫");
        hashMap.put("dog","小狗");
        hashMap.put("pig","小猪");
        hashMap.put("duck","小鸭");
        hashMap.put("monkey","小猴");
        String response = hashMap.getOrDefault(request,"词典中没有该词哦~");
        response += "\n";
        return response;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer_Dic dic = new TcpEchoServer_Dic(9090);
        dic.start();
    }
}
